package com.sinvo.oa.util;

import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.result.ResultCode;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Description jwt工具类
 */
public class JwtUtils {
    //过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    //签名密钥
    private static String tokenSignKey = "oa_system";
    //根据userid和username生成token
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //从token中获取userid
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                throw new CustomException(ResultCode.DATA_ERROR.getCode(),"令牌为空");
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"令牌格式错误");
        }
    }

    //从token中获取username
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) {
                throw new CustomException(ResultCode.DATA_ERROR.getCode(),"令牌为空，请登录");
            }

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"令牌格式错误");
        }
    }

    public static void main(String[] args) {
        String token = JwtUtils.createToken(1L, "admin");
        System.out.println(token);
        System.out.println(JwtUtils.getUserId(token));
        System.out.println(JwtUtils.getUsername(token));
    }
}
